import "package:dio/dio.dart";
import 'dart:async';
import 'dart:io';
import '../config/service_url.dart';

Response response;
Dio dio = new Dio();

Future getHomePageContext() async {
  try {
    print('开始请求数据');
    //请求类型
    dio.options.contentType =
        ContentType.parse("application/x-www-form-urlencoded").toString();
    //请求数据
    var formData = {'name': 'zyl', 'age': 18};
    response = await dio.post(servicePath['homePageContext'], data: formData);
    if (response.statusCode == 200) {
      return response.data;
    } else {
      throw Exception('后端接口出现异常，请检查代码和服务器情况。。。。');
    }
  } catch (e) {
    return print('ERROR:==========>${e}');
  }
}

//获取首页轮播图
Future getHomeCommodity() async {
  try {
    dio.options.contentType =
        ContentType.parse("application/x-www-form-urlencoded").toString();
    dio.options.responseType = ResponseType.json;
    // dio.options.contentType = ContentType.json.toString();
    response = await dio.post(servicePath['homePageCommodity']);
    if (response.statusCode == 200) {
      return response.data;
    } else {
      throw Exception("后台接口异常。。。");
    }
  } catch (e) {}
}

//获取nav导航分类
Future getNavigator() async {
  try {
    response = await dio.post(servicePath['homeTopNavigator']);
    if (response.statusCode == 200) {
      return response.data;
    } else {
      throw Exception("后台接口异常。。。");
    }
  } catch (e) {
    return print("ERROR:=============>${e}");
  }
}

//
Future getUrl(url) async {
  try {
    response = await dio.post(url);
    if (response.statusCode == 200) {
      return response.data;
    } else {
      throw Exception("后台接口异常。。。");
    }
  } catch (e) {
    return print("ERROR:=============>${e}");
  }
}

Future getCommodityPage(page) async {
  try {
    if (page == null) {
      page = 1;
    }
    //请求数据
    var formData = {'page': page};
    dio.options.contentType =
        ContentType.parse("application/x-www-form-urlencoded").toString();
    response = await dio.post(servicePath['commodityPage'], data: formData);
    if (response.statusCode == 200) {
      return response.data;
    } else {
      throw Exception("后台接口错误。。。。");
    }
  } catch (e) {
    return print("ERROR:=============>${e}");
  }
}

Future getRequest(String url, var formData) async {
  try {
    dio.options.contentType =
        ContentType.parse("application/x-www-form-urlencoded").toString();
    response = response = await dio.post(url, data: formData);
    if (response.statusCode == 200) {
      return response.data;
    } else {
      return "后台接口错误";
    }
  } catch (e) {
    return print("ERROR:=======>${e}");
  }
}
